package com.kly.smartbi.utils;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
@Slf4j
public class BloomFilterUtil {

    @Resource
    private RedissonClient redissonClient;

    /**
     * 创建布隆过滤器
     *
     * @param filterName         过滤器名称
     * @param expectedInsertions 预测插入数量
     * @param falsePositiveRate  误判率
     */
    public <T> RBloomFilter<T> create(String filterName, long expectedInsertions, double falsePositiveRate) {
        log.info("创建布隆过滤器：{}", filterName);
        RBloomFilter<T> bloomFilter = redissonClient.getBloomFilter(filterName);
        bloomFilter.tryInit(expectedInsertions, falsePositiveRate);
        return bloomFilter;
    }


    /**
     * 获取布隆过滤器
     * @param filterName
     * @return
     * @param <T>
     */
    public <T> RBloomFilter<T> get(String filterName) {
        log.info("获取布隆过滤器：{}", filterName);
        return redissonClient.getBloomFilter(filterName);
    }


    /**
     * 添加元素
     * @param bloomFilter
     * @param values
     * @param <T>
     */
    public <T> void add(RBloomFilter<T> bloomFilter, List<T> values) {
        for (T value : values) {
            bloomFilter.add(value);
        }
    }
}
